const apeWeChatPay = require("ape-node-wechatpay-v3");
const WxPay = require("wechatpay-node-v3");
const fs = require("fs");
const path = require("path");

// 创建 weChatPay 实例
const parentDir = path.resolve(__dirname, "../..");
const pay = new WxPay({
  appid: "wx94da07422597ebc2",
  mchid: "1683029327",
  authType: "WECHATPAY2-SHA256-RSA2048",
  publicKey: fs.readFileSync(parentDir + "/certificate/apiclient_cert.pem"), // 公钥
  privateKey: fs.readFileSync(parentDir + "/certificate/apiclient_key.pem"), // 秘钥
  serial_no: "371096946ECBA77C00AB030AF63622A166AD9D53",
  key: "E3rQKBMwtyHnVTGuilbuIrG5Elm3Fftn",
});

const weChatPay = new apeWeChatPay({
  appid: "wx94da07422597ebc2",
  mchid: "1683029327",
  serial_no: "371096946ECBA77C00AB030AF63622A166AD9D53",
  authType: "WECHATPAY2-SHA256-RSA2048",
  apiclientCert: fs.readFileSync(parentDir + "/certificate/apiclient_cert.pem"),
  apiclientkey: fs.readFileSync(parentDir + "/certificate/apiclient_key.pem"),
  certPath: parentDir + "/certificate",
  APIv3: "E3rQKBMwtyHnVTGuilbuIrG5Elm3Fftn",
});

class wxPay {
  // 获取签名值
  static async signature(params) {
    let signature = await weChatPay.getSignature(
      params.method,
      params.path,
      Math.floor(Date.now() / 1000),
      params.nonce_str,
      params.body
    );
    return signature;
  }

  // 获取 HTTP Authorization 头
  static async authorization(params) {
    const signature = await wxPay.signature(params);
    let authorization = weChatPay.getAuthorization(
      params.nonce_str,
      Math.floor(Date.now() / 1000),
      signature
    );
    return authorization;
  }
  // 下载微信支付平台证书
  static async getWeChatPayCert(params) {
    let result = {};
    try {
      result = await weChatPay.getWeChatPayCert();
    } catch (error) {
      console.log(error);
    }
    console.log(result);
  }

  // 支付回调验证签名
  static async verifySignature(body, Headers) {
    let result = null;
    try {
      result = await weChatPay.verifySignature(
        Headers["wechatpay-signature"], // 应答签名
        Headers["wechatpay-serial"], // 平台证书序列号
        Headers["wechatpay-timestamp"], // 生成签名的时间戳
        Headers["wechatpay-nonce"], // 应答随机串
        body
      );
    } catch (error) {
      return error;
    }
    return result;
    // { code: 200, msg: '验签名串和签名验证通过' }
  }

  // 回调解密
  static async decrypt(Body) {
    let data = null;
    try {
      data = await weChatPay.decrypting(
        Body.resource.ciphertext, // 结果数据密文
        Body.resource.nonce, // 加密使用的随机串
        Body.resource.associated_data // 附加数据
      );
    } catch (error) {
      return error;
    }
    return data;
    // { code: 200, data: xxxx(解密的数据), msg: '解密成功' }
  }

  // Jsapi
  static async Jsapi(res) {
    let data = {
      appid: "wx94da07422597ebc2",
      mchid: "1683029327",
      description: res.description,
      out_trade_no: res.out_trade_no,
      notify_url: "https://cellsplus.top/admin/wxpay/notify",
      amount: {
        total: res.total,
      },
      payer: {
        openid: res.openid,
      },
    };
    return await weChatPay.jsapiPay(data);

    // console.log(result);
    // 正常返回如下示例(data中包含jsapi支付客户端（小程序或者网页）所需要的全部参数)
    // {
    //   code: 200,
    //   data: {
    //     appid: 'xxxxxx',
    //     timeStamp: 'xxxxxx',
    //     nonceStr: 'xxxxxx',
    //     package: 'prepay_id=xxxxxx',
    //     signType: 'RSA',
    //     paySign: 'xxxxxx'
    //   },
    //   msg: 'success'
    // }
  }
}
module.exports = {
  wxPay,
  pay,
};
